JS中 “is not defined” 如何判断defined,defined和undefined 的区别

您所在的位置:网站首页 workbook is not defined JS中 “is not defined” 如何判断defined,defined和undefined 的区别

JS中 “is not defined” 如何判断defined,defined和undefined 的区别

2023-07-02 05:54| 来源: 网络整理| 查看: 265

JS中 “is not defined” 我今天找了一些资料和自己试验了各种方法,都不能得到正解,故写了这个问题的解决方案。

首先什么是is not defined?

从字面意思上来讲就是未定义,也就是未申明。就是这个变量(对象)压根就没有。如下:

  console.log(sojson);//sojson is not defined

可能还一知半解,我们继续往下看。

is not defined 和 undefined 区别。

我们大多数人都知道 undefined  ,却不知道 defined  , undefined  是未定义,如下:

  var so; console.log(so);//undefined console.log(so.a);//so.a is undefined

这个时候输出的是 undefined  。访问变量的属性就会提示is undefined 就是这个变量so 未定义值(类型);

而defined 呢,如下:

  console.log(so);//so is not defined

其实如果理解一下其实就是未申明。也就是可以理解变量的过程是,先声明后赋值,在赋值的过程中确定了这个变量的类型。

所以总结一下:is not defined 优先于 undefined ,也就是先判断这个对象是否申明了,如果没申明直接就 is not defined,如果已经申明,那么再看有没有赋值(类型),如果没有那么就是 undefined 或者 访问对象的属性就是 is undefined 。

is not defined 如何避免

比如我们常用的 jquery  ,如果出现了jQuery is not defined  ,或者$ is not defined  ,那么我们按以下步骤来排查:

是否引入了 jQuery  (注意是否404)。 jQuery 是否在依赖 jQuery  的 js  之前引用(因为js加载是自上而下加载)。 是否过多引入jQuery ,或者引入多个版本的jQuery 。

我们自己定义对象的时候,对外要提供方法,如下:

  //申明局部变量 so。 var so = { a : function(){}; } //对外提供访问。 window.so = so; 如何判断 undefined。

undefined 很好判断,如下:

  var sojson; console.log(sojson == undefined);//true console.log(sojson === undefined);//true; console.log(typeof sojson == 'undefined');//true console.log(typeof sojson === 'undefined');//true console.log(!sojson);//true //... ... 如何判断is not defined

我在网上没找到合适的资料来判断“is not defined”,我项目中因为是公共js需要解决,对象是否定义。都不好判断。所以我用比较low的方式来判断的,如果你有好的点子,请留言或者告知我,我加上。

  try{ var x = sojson.demo; }catch(e){ console.log(e.message);//sojson is undefined }

因为抛出了Exception ,所以能catch ,进入了catch 模块。如果有多个,请分开cache ,如下:

  try{ var x = sojson.demo; }catch(e){ console.log(e.message);//sojson is undefined } try{ var y = sojson.y; }catch(e){ console.log(e.message);//sojson is undefined }

因为出现一个 Exception  ,就不会往下执行了,所以要分开去处理。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3